import '../css/index.css';
import '../fonts/iconfont.css';
import ajax from '../untils/ajax';

car1();
function car1() {
  let swiper = new Swiper(".mySwiper", {
    spaceBetween: 30,
    centeredSlides: true,
    autoplay: {
      delay: 3500,
      disableOnInteraction: false,
      pauseOnMouseEnter: true,
    },
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
}

car2();
function car2() {
  var swiper = new Swiper('.swiper-container', {
    slidesPerView: 3,
    spaceBetween: 30,
    centeredSlides: true,
    loop: true,
    autoplay: {
      delay: 3000,
      disableOnInteraction: false,
      pauseOnMouseEnter: true,
    },
  });
}

goodsNoData();
function goodsNoData() {
  let goods = document.querySelectorAll('.goods-goods');
  for (let i = 0; i < goods.length; i++) {
    goods[i].innerHTML = `
    <img src="https://s1.328888.xyz/2022/09/14/cTrwg.png">
    <h2>商品名称</h2>
    <h4>成色</h4>
    <h3>￥价格</h3>
    `
  }
}

goodsHaveData();
function goodsHaveData() {
  ajax('get', '/api/users/getGoods').then(result => {
    let goods = document.getElementsByClassName('goods-goods');
    console.log(result.data);
    const arr = result.data;
    for (let j = 0; j < goods.length; j++) {
      let path = arr[j].img.slice(7);
      goods[j].innerHTML = `
    <img src="http://127.0.0.1:3000\\${path}">
    <h2>${arr[j].name}</h2>
    <h4>${arr[j].fineness}</h4>
    <h3>￥${arr[j].price}</h3>
    `;
      goods[j].dataset.id = arr[j]._id;
      goods[j].onclick = function () {
        window.open(`goodsinfo.html?id=${arr[j]._id}`)
      }
    }


  }).catch(err => {
    console.log(err);
  })
}


toTop();
function toTop() {
  const topBtn = document.getElementById("barTotop");
  topBtn.onclick = function () {
    console.log('top');
    let timer = null;
    cancelAnimationFrame(timer);
    timer = requestAnimationFrame(function fn() {
      let oTop = document.body.scrollTop || document.documentElement.scrollTop;
      if (oTop > 0) {
        scrollTo(0, oTop - 100);
        timer = requestAnimationFrame(fn);
      } else {
        cancelAnimationFrame(timer);
      }
    });
  }
}


showScroll();
function showScroll() {
  window.addEventListener('scroll', function () {
    let num = window.pageYOffset;
    const bar = document.querySelectorAll('.goodsbars');
    const bar0 = document.getElementById('bar2');
    bar0.className

    if (num < 800 || num > 3300) {
      bar0.style.display = 'none';
    } else {
      bar0.style.display = 'flex';
    }
    if (num > 893 && num < 1304) {
      bar[0].innerHTML = '家居用品';
      bar[0].style.color = '#00bbad';
      bar[0].style.backgroundColor = '#fff'
    } else {
      bar[0].innerHTML = '家居用品';
      bar[0].style.color = '#fff';
      bar[0].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
    if (num > 1304 && num < 1713) {
      bar[1].innerHTML = '美妆美容';
      bar[1].style.color = '#00bbad';
      bar[1].style.backgroundColor = '#fff'
    } else {
      bar[1].innerHTML = '美妆美容';
      bar[1].style.color = '#fff';
      bar[1].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
    if (num > 1713 && num < 2124) {
      bar[2].innerHTML = '汽摩生活';
      bar[2].style.color = '#00bbad';
      bar[2].style.backgroundColor = '#fff'
    } else {
      bar[2].innerHTML = '汽摩生活';
      bar[2].style.color = '#fff';
      bar[2].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
    if (num > 2124 && num < 2533) {
      bar[3].innerHTML = '手机数码';
      bar[3].style.color = '#00bbad';
      bar[3].style.backgroundColor = '#fff'
    } else {
      bar[3].innerHTML = '手机数码';
      bar[3].style.color = '#fff';
      bar[3].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
    if (num > 2533 && num < 2944) {
      bar[4].innerHTML = '图书杂志';
      bar[4].style.color = '#00bbad';
      bar[4].style.backgroundColor = '#fff'
    } else {
      bar[4].innerHTML = '图书杂志';
      bar[4].style.color = '#fff';
      bar[4].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
    if (num > 2944 && num < 3300) {
      bar[5].innerHTML = '运动户外';
      bar[5].style.color = '#00bbad';
      bar[5].style.backgroundColor = '#fff'
    } else {
      bar[5].innerHTML = '运动户外';
      bar[5].style.color = '#fff';
      bar[5].style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
    }
  });
}

showMRL();
function showMRL() {
  const ptpBtn = document.getElementById('headWsale');
  const NullBtn = document.getElementById('ptpNull');
  const loginBtn = document.getElementById("topLogin");
  const regBtn = document.getElementById("topReg");
  const goR = document.getElementById('goRegBox');
  const goL = document.getElementById('goLoginBox');

  const loginBox = document.getElementById('loginBox');
  const regBox = document.getElementById('regBox');
  const ptpBox = document.getElementById('ptp');

  const M = document.getElementById('blackM');

  NullBtn.onclick = function () {
    ptpBox.style.display = 'none';
    M.style.display = 'none';
  }

  ptpBtn.onclick = function () {
    console.log('ptp');
    ptpBox.style.display = 'block';
    M.style.display = 'block';
  }
  loginBtn.onclick = function () {
    console.log('loginBox');
    loginBox.style.display = 'block';
    M.style.display = 'block'
  }
  regBtn.onclick = function () {
    console.log('regBox');
    regBox.style.display = 'block';
    M.style.display = 'block'
  }
  M.onclick = function () {
    M.style.display = 'none';
    ptpBox.style.display = 'none';
    loginBox.style.display = 'none';
    regBox.style.display = 'none';
  }
  goR.onclick = function () {
    loginBox.style.display = 'none';
    regBox.style.display = 'block';
  }
  goL.onclick = function () {
    regBox.style.display = 'none';
    loginBox.style.display = 'block';
  }
}

test();
function test() {
  const barBtn = document.getElementById('barHelp');
  barBtn.onclick = function () {
    location.assign('goodsinfo.html')
  }
}

gotoGoods();
function gotoGoods() {
  const menu = document.getElementById('menu');
  menu.onclick = function () {
    location.assign('goods.html')
  }
}

// 图片上传与预览
const form = document.forms[0];
const uploadfile = document.getElementById('uploadfile');


uploadfile.onchange = show_uploadImg;
form.onsubmit = uploadGoods;


if (typeof FileReader == "undified") {
  alert("您老的浏览器不行了！");
}




function show_uploadImg() {
  var resultFile = document.getElementById("uploadfile").files[0];
  if (resultFile) {
    var reader = new FileReader();
    reader.readAsDataURL(resultFile);
    reader.onload = function (e) {
      var urlData = this.result;
      document.getElementById("result").src = urlData;
      // document.getElementById("result").alt= resultFile.name ;



    }

  }
}



function uploadGoods(e) {

  e.preventDefault();
  const xhr = new XMLHttpRequest();
  const fd = new FormData(form);

  xhr.open('post', 'api/users/addgoods', true);

  xhr.send(fd);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        alert("发布成功")
        location.assign("index.html")
      } else {
        console.log('错误')
      }
    }
  };

}


login_reg();
function login_reg() {
  const regBox = document.querySelector('#regBox');
  const loginBox = document.querySelector('#loginBox');
  const form = document.querySelector('#regBox form');
  const form2 = document.querySelector('#loginBox form');

  form.onsubmit = e => {
    e.preventDefault();
    const username = form.username.value;
    const password = form.password.value;
    ajax('post', '/api/users/reg?', { username, password }).then(result => {
      if (result.flag) {
        alert('注册成功，请登录');
        regBox.style.display = "none"
        loginBox.style.display = "block"
      } else {
        alert(result.msg);
        form.username.select();
        form.username.focus();
      }
    }).catch(err => {
      alert('服务器出错', err);
    })

  }

  form2.onsubmit = e => {
    e.preventDefault();
    const username = form2.username.value;
    const password = form2.password.value;
    if (username && password) {
      ajax('post', '/api/users/login', {
        username: form2.username.value,
        password: form2.password.value
      }).then(result => {
        if (result.flag) {
          alert('登录成功')
          localStorage.setItem('token', result.token);
          location.assign('index.html')
        } else {
          alert(result.msg)
        }
      })
    } else {
      alert('请填写表单每一项')
    }
  }
}

toggle();
function toggle() {
  const toggle = document.querySelector('.toggle');
  const bow = document.querySelector('#bow');
  const bowReg = document.querySelector('#bowReg');
  const clear = document.querySelector('.clear');
  let login = localStorage.getItem("token")
  bow.style.display = "none"

  if (login) {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          toggle.style.display = "none"
          bow.style.display = "inline-block"
          bowReg.innerHTML = '用户:' + xhr.response.username;
          alert('欢迎您：' + xhr.response.username)
        }
      }
    };

    xhr.open('get', `/api/users/index`, true);
    // 设置请求头
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    xhr.responseType = "json";
    xhr.send();
  }

  clear.onclick = () => {
    if (confirm("您是否退出账号")) {
      localStorage.clear()
      alert("已退出")
      location.replace('./')
    }
  }
}